<template>
  <div class="Reigster">
    <nav-bar :title="title" :left-arrow="true"></nav-bar>
    <div class="formBox">
      <van-form @submit="onSubmit">
        <van-field
          v-model="username"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="registRules.password"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { regist } from '@/api/user'
import NavBar from '@/components/NavBar/index'
import { mapMutations } from 'vuex'
export default {
  name: 'Tabs',
  components: {
    NavBar
  },
  data () {
    return {
      title: '注册',
      username: '',
      password: '',
      idNum: '',
      carId: '',
      params: {},
      registRules: {
        password: [
          { required: true, message: '', trigger: 'onBlur' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/, message: '密码至少8个字符，至少1个大写字母，1个小写字母和1个数字' }
        ]
      }
    }
  },
  methods: {
    ...mapMutations([
      'setLogin',
      'setUser'
    ]),
    async onSubmit (values) {
      for (var key of Object.keys(values)) {
        if (key === '密码') {
          this.params.password = values[key]
        } else {
          this.params.username = values[key]
        }
      }
      const { data: res } = await regist(this.params)
      console.log(res)
      if (res.meta.status === 200 && res.data !== null) {
        this.params.isDetail = false
        this.params.userId = res.data
        // 发送登录请求
        this.setLogin(true)
        this.setUser(this.params)
        this.$notify({ type: 'success', message: '注册登录成功，页面即将跳转' })
        setTimeout(() => {
          this.$router.push('/detail')
        }, 1000)
      } else if (res.data === null) {
        this.$notify({ type: 'danger', message: '账号已存在' })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.img{
  margin-top: 20px;
  height: 200px;
  width: 100%;
  img{
    width: 100%;
    height: 100%;
  }
}
.formBox{
  margin-top: 5%;
}
</style>
